var args = arguments[0] || {};
var ViewNavigator = require('utils/ViewNavigator');

var InvitationModel = require('viewmodel/InvitationModel');

var fb = Alloy.Globals.Facebook;
var friendsToInvite = new Object();
var IMG_CHECKED = "/images/check_nuevo_contacto.png";
var IMG_NOT_CHECKED = "/images/agregar_contacto_nuevo_grupo.png";
var listItems;

var Search = function(args) {
	init();
};

function init() {
	$.searchWindow.addEventListener("open", retrieveFriendsFromFacebook);
	$.invite.addEventListener("click", inviteFriends);
	$.search.addEventListener("change", searchFriends);
	$.userFriendsContainer.addEventListener("itemclick", function(e) {
		addFriendToInvite(e.itemIndex);
	});
};

// Obtiene a los amigos de Facebook
function retrieveFriendsFromFacebook() {
	var localFb = fb;
	var params = {
		'limit' : LIMIT,
		'fields' : 'id,name,picture'
	};

	localFb.requestWithGraphPath("/me/friends", {
		"fields" : "id, name, picture"
	}, "GET", function(res) {
		var friends = [];
		var friendsList = JSON.parse(res.result).data;

		if (!res.success) {
			alert(L('error_load_friends'));
			ViewNavigator.goHome();
			return;
		}

		for (var i = 0; i < friendsList.length; i++) {
			var friend = {
				id : friendsList[i].id,
				name : {
					text : friendsList[i].name
				},
				picture : {
					image : friendsList[i].picture.data.url
				},
				check : {
					image : IMG_NOT_CHECKED
				},
				target : friendsList[i]
			};
			// if (!isAnExistingUser(args, friend)) {
				friends.push(friend);
			// }
		}

		$.friendsList.setItems(friends);
		listItems = friends;
	});
}

// Selecciona el amigo para invitar
function addFriendToInvite(itemIndex) {
	var item = $.friendsList.getItemAt(itemIndex);
	var friendId = item.id;

	if (friendsToInvite[friendId]) {
		delete friendsToInvite[friendId];
		item.check.image = IMG_NOT_CHECKED;
	} else {
		friendsToInvite[friendId] = item;
		item.check.image = IMG_CHECKED;
	}
	$.friendsList.updateItemAt(itemIndex, item);
	listItems[itemIndex] = item;
};

// Envía los amigos seleccionados a la vista SelfieView
function inviteFriends() {
	var listInvited = [];
	var listInvited2 = [];
	for (var friendId in friendsToInvite) {
		var userToInvite = {
			externalId : friendsToInvite[friendId].target.id,
			name : friendsToInvite[friendId].target.name

		};
		listInvited.push(userToInvite);
		listInvited2.push(friendsToInvite[friendId].target);
	}
	var callbackSucceded = function(data) {
		// alert("Search" + JSON.stringify(data));
	};
	var callbackError = function(error) {
		alert(error);
	};
	//JSON.stringify({ usie: args.usie}) + JSON.stringify({ listInvited: listInvited });
	var dataToSend = {
		usieId : args.usie.id,
		listInvited : listInvited
	};
	// alert("Search" + JSON.stringify(dataToSend));
	InvitationModel.createInvitation(dataToSend, callbackSucceded, callbackError);

	ViewNavigator.goBack();
	Ti.App.fireEvent("invite", {
		listInvited : listInvited2
	});
}

// Filtra los amigos ya cargados desde Facebook
function searchFriends() {
	var inputSearch = this.value, inputTotalChars = inputSearch.length;
	var arr = new Array();

	for (var i = 0, j = listItems.length; i < j; i++) {
		var completeName = listItems[i].name.text.toLowerCase();
		var splittedName = completeName.split(" ");
		for (var k = 0; k < splittedName.length; k++) {
			if (splittedName[k].substr(0, inputTotalChars) === inputSearch || listItems[i].check.image === IMG_CHECKED) {
				arr.push(listItems[i]);
				break;
			}
		}
	}

	$.friendsList.setItems(arr);
}

// function isAnExistingUser(friendFromArgs, crtUser) {
	// var isAnExistingUser /*: Boolean */;
// 
	// if (friendFromArgs && crtUser) {
		// alert("entre");
		// alert(crtUser.name);
		// for (var i = 0; i < friendFromArgs.length; i++) {
			// alert(crtUser.name);
			// alert(friendFromArgs[i].name);
			// if (crtUser.id === friendFromArgs[i].id) {
				// isAnExistingUser = true;
			// }
		// }
	// }
// 
	// return isAnExistingUser || false;
// }

$.view = new Search(args);

